<template>


  <div class="app-container">


    <el-card shadow="always" style="margin-top: 20px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="160px">
    <el-row :gutter="20">
      <el-col :span="22">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="研究领域" prop="researchField">
            <el-input
              v-model="queryParams.researchField"
              placeholder="请输入研究领域"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="所属方向" prop="deptId">
            <el-select v-model="queryParams.deptId" placeholder="请选择所属研究方向" clearable>
                <el-option
                  v-for="dept in deptList"
                  :key="dept.deptId"
                  :label="dept.deptName"
                  :value="dept.deptId"
                />

              </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="projectLeader">
            <el-input
              v-model="queryParams.projectLeader"
              placeholder="请输入负责人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

        </el-col>
        <el-col :span="24">

        <el-form-item label="立项时间">
        <el-date-picker
          v-model="daterangeApprovalTime"
          style="width: 208px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
		    </el-form-item>


        </el-col>
      </el-row>
      </el-col>

      <!-- 第二列 -->
      <el-col :span="2">
        <el-row>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
      </el-col>
      </el-row>
    </el-form>
    </el-card>
    <el-card shadow="always" style="margin-top: 20px;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:projectInfo:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:projectInfo:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="立项项目名"  width="150" align="center" prop="projectName" />
      <el-table-column label="研究领域" align="center" prop="researchField" />
      <el-table-column label="所属方向" align="center" width="160" prop="deptId">
        <template slot-scope="scope">
          {{ getDeptLabel(scope.row.deptId) }}
        </template>
      </el-table-column>
      <el-table-column label="项目负责人"  width="100" align="center" prop="projectLeader" />
      <el-table-column label="立项时间" align="center" prop="approvalTime" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startDate" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目结束时间" align="center" prop="endDate" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="项目经费(万元)"
          align="center"
          prop="funding"
           width="120"
        >
        <template slot-scope="scope">
          ¥{{ scope.row.funding ? scope.row.funding.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '0.00' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="项目进度" width="100" align="center" prop="progress" >
        <template slot-scope="scope">
          <el-progress :text-inside="true" :stroke-width="28" :percentage="scope.row.progress"></el-progress>
        </template>
      </el-table-column> -->
      <el-table-column label="项目状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_pjt_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="联系电话"  width="110" align="center" prop="phone" />
      <el-table-column label="操作"  width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #409EFF;"

              @click="handleView(scope.row)"
              v-hasPermi="['system:projectInfo:query']"
            >查看</el-button>

            <el-button
              type="text"
              :style="{ color: (scope.row.status === '1' || scope.row.status === '2') ? '#E6A23C' : '#909399' }"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:projectInfo:edit']"
              :disabled="!(scope.row.status === '1' || scope.row.status === '2')"
            >
              {{ (scope.row.status === '1' || scope.row.status === '2') ? '修改' : '已立项' }}
            </el-button>


          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </el-card>


    <!-- 添加或修改项目征集发布对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body
     @close="handleDialogClose">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-card shadow="always" style="margin: 20px;" >
          <div class="dialog-content">

            <!-- 步骤条 -->
            <el-steps :active="activeStep" finish-status="success" align-center style="margin-bottom: 20px;">
              <el-step title="基本信息"></el-step>
              <el-step title="课题分解"></el-step>
              <el-step title="项目成员"></el-step>
              <el-step title="任务分解"></el-step>
              <el-step title="项目预算"></el-step>
              <el-step title="年度经费构成"></el-step>
              <el-step title="附件文档"></el-step>
            </el-steps>

            <!-- 步骤内容容器 -->
            <div class="step-content">
              <div v-show="activeStep === 0">
                <el-divider><i class="el-icon-collection"></i> 基本信息</el-divider>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="项目名称" prop="projectName">
                      <el-input v-model="form.projectName" placeholder="请输入项目名称" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="研究领域" prop="researchField">
                      <el-input v-model="form.researchField" placeholder="请输入研究领域" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="所属方向" prop="deptId">
                      <el-select v-model="form.deptId" placeholder="请选择所属方向" clearable style="width: 100%">
                        <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="负责人" prop="projectLeader">
                      <el-input v-model="form.projectLeader" placeholder="请输入负责人" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="立项时间" prop="approvalTime">
                      <el-date-picker v-model="form.approvalTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择立项时间" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="开始时间" prop="startDate">
                      <el-date-picker v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="结束时间" prop="endDate">
                      <el-date-picker v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="经费(万元)" prop="funding">
                      <el-input v-model="form.funding" placeholder="请输入经费" style="width: 100%">
                        <template slot="append">万元</template>
                      </el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="联系电话" prop="phone">
                      <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" show-word-limit prefix-icon="el-icon-mobile" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <div v-show="activeStep === 1">
                <el-divider content-position="center">课题信息</el-divider>
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSciProjectTopic">添加</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSciProjectTopic">删除</el-button>
                  </el-col>
                </el-row>

                <el-table :data="sciProjectTopicList" @selection-change="handleSciProjectTopicSelectionChange">
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column label="课题名称" prop="topicName">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.topicName" placeholder="请输入课题名称" />
                    </template>
                  </el-table-column>
                  <el-table-column label="承担单位" prop="undertakingUnit" width="260">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.undertakingUnit" placeholder="请输入承担单位" />
                    </template>
                  </el-table-column>
                  <el-table-column label="负责人" prop="leader" width="150">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.leader" placeholder="请输入负责人" />
                    </template>
                  </el-table-column>
                  <el-table-column label="任务总经费(万元)" prop="totalFunding" width="150">
                    <template slot-scope="scope">
                       <el-input v-model="scope.row.totalFunding" placeholder="请输入总经费" />
                    </template>
                  </el-table-column>
                  <el-table-column label="财政专项经费(万元)" prop="specialFunding" width="150">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.specialFunding" placeholder="请输入总经费" />
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div v-show="activeStep === 2">
                <el-divider content-position="center">项目成员信息</el-divider>
                <ProjectMember ref="projectMember" :projectId="form.id" :sciProjectTopicList="intactTopicList" @update:memberData="handleMemberDataUpdate"/>
              </div>

              <div v-show="activeStep === 3">
                <el-divider content-position="center">任务分解</el-divider>
                <ProjectTask ref="projectTask" :projectId="form.id"   @update:taskData="handleTaskDataUpdate"/>
              </div>
              <div v-show="activeStep === 4">
                <el-divider content-position="center">项目预算</el-divider>
                <BudgetTemplateSelector
                ref="budgetComponent"
                  :projectId="form.id"
                  :topics="intactTopicList"
                  @submit="handleBudgetSubmit"
                />
              </div>
              <div v-show="activeStep === 5">
                <el-divider content-position="center">年度经费构成</el-divider>
                <FundingAnnual
                  :projectId="form.id"
                  :sciFundingAnnualList="sciFundingAnnualList"
                  @update:fundingAnnualData="handleFundingAnnualDataUpdate"
                />
              </div>

              <div v-show="activeStep === 6">
                <el-divider><i class="el-icon-folder-opened"></i> 附件文档</el-divider>
                <file-upload-table v-model="form.fileRows" :show-add="true" />
              </div>
            </div>


          </div>
          </el-card>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="prevStep" v-if="activeStep > 0">上一步</el-button>
          <el-button type="success" @click="submitForm" v-if="activeStep === 6">提 交</el-button>
          <el-button type="primary" @click="nextStep" v-else>下一步</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>





    <el-drawer
      title="立项信息"
      :visible.sync="drawer"
      size="60%"
      @close="cancelView">

      <el-card shadow="always" style="margin: 20px;" class="black-bold-header">
        <div slot="header" class="clearfix">
            <span>基本信息</span>
          </div>
        <el-descriptions  border  :column="2">
          <el-descriptions-item label="项目名称"  > {{formView.projectName}}</el-descriptions-item>
          <el-descriptions-item label="研究领域">{{ formView.researchField }}</el-descriptions-item>
          <el-descriptions-item label="所属方向">{{getDeptLabel(formView.deptId) }}</el-descriptions-item>
          <el-descriptions-item label="负责人"  > {{formView.projectLeader}}</el-descriptions-item>
          <el-descriptions-item label="立项时间">{{ formView.approvalTime }}</el-descriptions-item>

		      <el-descriptions-item label="开始时间"  > {{formView.startDate}}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formView.endDate }}</el-descriptions-item>
          <el-descriptions-item label="经费(万元)">
            ¥{{ formView.funding ? formView.funding.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '0.00' }}
           </el-descriptions-item>
          <!-- <el-descriptions-item label="进度">
            <el-progress :percentage="formView.progress" :text-inside="true" :stroke-width="26" style="width: 50%"></el-progress>
          </el-descriptions-item> -->
          <el-descriptions-item label="状态">
            <dict-tag :options="dict.type.sci_pjt_status" :value="formView.status"/>
          </el-descriptions-item>
		      <el-descriptions-item label="联系电话"  > {{this.formView.phone}}</el-descriptions-item>
        </el-descriptions>
      </el-card>

       <!-- 课题任务信息 -->
      <el-card  shadow="always" style="margin: 20px;" class="black-bold-header">
          <div slot="header" class="clearfix">
            <span>课题信息</span>
          </div>
          <el-table :data="formView.sciProjectTopicList" style="width: 100%">
            <el-table-column prop="topicName" label="课题名称"></el-table-column>
             <el-table-column prop="undertakingUnit" label="承担单位" width="300"></el-table-column>
            <el-table-column prop="leader" label="负责人" width="150"></el-table-column>
            <el-table-column prop="totalFunding" label="任务总经费(万元)"  width="150"></el-table-column>
            <el-table-column prop="specialFunding" label="财政专项经费(万元)"  width="150"></el-table-column>
          </el-table>
      </el-card>

      <!-- 项目成员信息 -->
      <el-card  shadow="always" style="margin: 20px;" class="black-bold-header">
        <div slot="header" class="clearfix">
          <span>成员信息</span>
        </div>
        <ProjectMember :projectId="formView.id" :viewFlag=true />
        <!-- <el-table :data="formView.sciProjectMemberList" style="width: 100%">
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column label="性别" align="center" prop="gender" />
          <el-table-column label="身份证号" align="center" prop="idCard" width="170"  />
          <el-table-column label="技术职称" align="center" prop="technicalTitleCode" />
          <el-table-column label="职务" align="center" prop="position" />
          <el-table-column label="学位" align="center" prop="degree" />
          <el-table-column label="专业" align="center" prop="major" width="150" />

          <el-table-column label="人员分类" align="center" prop="memberCategoryCode" />
          <el-table-column label="所属课题" align="center" prop="topicName" width="200"/>
          <el-table-column label="是否有工资性收入" align="center" prop="hasSalaryIncome" />
          <el-table-column label="工作单位" align="center" prop="workUnit" width="150"/>
          <el-table-column label="投入本项目的全时工作时间" align="center" prop="workloadManMonth" />
        </el-table> -->
      </el-card>


         <!-- 任务信息 -->
      <el-card  shadow="always" style="margin: 20px;" class="black-bold-header">
        <div slot="header" class="clearfix">
          <span>任务信息</span>
        </div>
        <ProjectTask :projectId="formView.id"  :viewFlag=true />
      </el-card>

      <el-card  shadow="always" style="margin: 20px;" class="black-bold-header">
        <div slot="header" class="clearfix">
          <span>预算信息</span>
        </div>
        <BudgetData  :projectId="formView.id"  />

      </el-card>

      <el-card  shadow="always" style="margin: 20px;" class="black-bold-header">
        <div slot="header" class="clearfix">
          <span>年度经费构成</span>
        </div>
        <FundingAnnual  :projectId="formView.id"  :viewFlag=true />

      </el-card>
      <!-- 附件文档信息 -->
      <el-card shadow="always" style="margin: 20px;" class="black-bold-header">
        <div slot="header" class="clearfix">
          <span>附件文档</span>
        </div>
        <el-descriptions :column="1" border>
          <el-descriptions-item v-for="(row, index) in formView.fileRows" :key="'file-' + index" :label="row.fileClassName || '未命名文件'">
            <div>
              <p>
                <template v-if="row.fileInfo && row.fileInfo.length > 0">
                  <div v-for="(file, fileIndex) in row.fileInfo" :key="fileIndex" style="margin-top: 5px;">
                    <el-link
                      type="primary"
                      target="_blank"
                       @click="handleDownload(file)"
                    >
                      {{ file.originalName }}
                    </el-link>

                    <span style="margin-left: 8px; color: #909399; font-size: 12px">
                      ({{ (file.fileSize/1024).toFixed(2) }} KB)
                    </span>
                  </div>
                </template>
                <span v-else style="color: #909399">无附件</span>
              </p>
              <p>上传人: {{ row.uploader }}</p>
              <p>上传时间: {{ row.uploadTime }}</p>

            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-drawer>


  </div>
</template>

<script>
import { listProjectInfo, getProjectInfo, delProjectInfo, addProjectInfo, updateProjectInfo } from "@/api/sci/projectInfo";
import { downloadMinioFile } from '@/api/common/common';
import { listDept } from '@/api/system/dept';
import { listAppSubmit, getAppSubmit} from "@/api/sci/appSubmit";
import  ProjectTask  from './task/index.vue';
import  ProjectMember  from './member/index.vue';
import BudgetTemplateSelector from './budget/index.vue';
import FileUploadTable from '@/views/sci/components/FileUploadTable';
import BudgetData from "./budget/budgetData.vue";
import FundingAnnual from "./fundingAnnual/index.vue";





export default {
  name: "ProjectEstablishment",
  dicts: ['sci_pjt_status','sci_member_role'],
  components: {
    ProjectTask,
    ProjectMember,
    BudgetTemplateSelector,
    FileUploadTable,
    BudgetData,
    FundingAnnual
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],

      // 子表选中数据
      checkedSciProjectTopic: [],

      checkedSciProjectMember: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目征集发布表格数据
      projectInfoList: [],

      // 科研项目课题表格数据
      sciProjectTopicList: [],

      // 编辑好完整的课题数据
      intactTopicList: [],

      sciProjectMemberList: [],

      sciProjectBudgetList: [],

      sciFundingAnnualList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      openMember: false,

	    daterangeApprovalTime: [],

      drawer: false,

      readonlyApplicationId: false, // 控制是否只读



      username : this.$store.state.user.nickName,

	    deptList: [],

      selectApplicationList: [],

      applicationList: [],

      taskData: null,

      applicationId: null,

      activeStep: 0,
      selectedTopicId: null,

      // 添加预算数据存储
      budgetData: [],


      isEditing: true, // 用于判断是否是编辑模式


      projectRoles: [
        { label: '负责人', value: 'leader' },
        { label: '成员', value: 'member' },
        { label: '课题负责人', value: 'topic_leader' },
        { label: '协作成员', value: 'collaborator' }
      ],

      // 查询参数
      queryParams: {
         pageNum: 1,
        pageSize: 10,
        projectName: null,
        researchField: null,
        deptId: null,
        projectLeader: null,
        startDate: null,
        approvalTime: null,
        progress: null,
        status: null,
        endDate: null
      },
      // 表单参数
      form: {
        id: null,
        projectName: null,
        researchField: null,
        deptId: null,
        projectLeader: null,
        approvalTime: null,
        startDate: null,
        endDate: null,
        funding: null,
        progress: null,
        status: null,
        phone: null,
        members: [], // 新增的成员列表
        sciProjectTopicList: [], // 新增的科研项目课题列表
        sciProjectMemberList: [], // 新增的科研项目成员列表
        sciProjectBudgetList: [], // 新增的科研项目成员列表
        sciProjectTaskList: [], // 新增的科研项目成员列表
        fileRows: [
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      },
      formView: {
        sciProjectTopicList: [], // 新增的科研项目课题列表
        sciProjectMemberList: [], // 新增的科研项目成员列表
        sciProjectBudgetList: [], // 新增的科研项目成员列表
        sciProjectTaskList: [], // 新增的科研项目成员列表
        fileRows: [] // 初始化为空数组
      },

      formData: {
        fileRows: [] // 初始化为空数组
      },
      // 表单校验
      rules: {
        applicationId: [

        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        researchField: [
          { required: true, message: "研究领域不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属方向不能为空", trigger: "blur" }
        ],
        projectLeader: [
          { required: true, message: "项目负责人不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],

        endDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],

        approvalTime: [
          { required: true, message: "立项时间不能为空", trigger: "blur" }
        ],
        funding: [
          { required: true, message: "项目经费不能为空", trigger: "blur" }
        ],
        // progress: [
        //   { required: true, message: "项目进度不能为空", trigger: "blur" }
        // ],
        status: [
          { required: true, message: "项目状态不能为空", trigger: "change" }
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        phone: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        fileRows: {
          fileClassName: [
            { required: true, message: '请选择文件名称', trigger: 'change' }
          ],

          fileInfo: [
            { required: true, message: '请上传附件', trigger: 'change' }
          ],
        },
        sciProjectMemberList: {

          nickName: [
            { required: true, message: '姓名不能为空', trigger: 'blur' }
          ],
          role: [
            { required: true, message: '角色不能为空', trigger: 'blur' }
          ]
        },
        sciProjectTopicList: {
          topicName: [
            { required: true, message: '课题名称不能为空', trigger: 'blur' }
          ],
          leader: [
            { required: true, message: '负责人不能为空', trigger: 'blur' }
          ]
        }
      },


    };
  },

   // 添加 provide 选项
  provide() {
    return {
      budgetDataManager: {
        updateBudgetData: this.updateBudgetData
      }
    };
  },
  created() {
    this.getList();
	  this.getDeptList();
    this.getApplicationList();
    this.loadProjectInfoData();
  },

  watch: {
    '$route'(to, from) {
      if (to.name === 'ProjectEstablishment') {
        this.loadProjectInfoData();
      }
    },
    projectInfoList: {
      deep: true,
      handler(newVal) {
        const establishedApplicationIds = newVal.map(p => p.applicationId);
        this.selectApplicationList = this.projectInfoList.filter(item => item.status !== 0 && !establishedApplicationIds.includes(item.id));
      }
    }
  },

  methods: {
    handleTaskDataUpdate(taskList) {
      this.sciProjectTaskList = taskList; // 存入父组件表单
      this.form.sciProjectTaskList = taskList; // 存入父组件表单
    },
    handleBudgetDataUpdate(budgetList) {
      this.sciProjectBudgetList = budgetList; // 存入父组件表单
      this.form.sciProjectBudgetList = budgetList; // 存入父组件表单
    },
    handleMemberDataUpdate(memberList) {
      this.sciProjectMemberList = memberList; // 存入父组件表单
      this.form.sciProjectMemberList = memberList; // 存入父组件表单
    },

    handleFundingAnnualDataUpdate(fundingList) {
      this.sciFundingAnnualList = fundingList; // 存入父组件表单
      this.form.sciFundingAnnualList = fundingList; // 存入父组件表单
      console.log('收到经费年度列表:', fundingList);
    },

    /** 查询项目征集发布列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeApprovalTime && '' != this.daterangeApprovalTime) {
        this.queryParams.params["beginApprovalTime"] = this.daterangeApprovalTime[0];
        this.queryParams.params["endApprovalTime"] = this.daterangeApprovalTime[1];
      }
      listProjectInfo(this.queryParams).then(response => {
        this.projectInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    loadProjectInfoData() {
      this.getApplicationList();
      this.applicationId = this.$route.query.id || this.$route.params.id;
      if (this.applicationId) {
        this.open = true;
        this.readonlyApplicationId = true;
        this.title = "添加立项管理";
        this.form.fileRows[0].uploader = this.username;

        this.getApplicationInfo();
      }
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.resetAllComponents();
    },
     cancelView() {
      this.drawer = false;
      this.resetView();
      this.resetAllComponents();
    },
    handleDialogClose() {
      this.open = false;
      this.reset();
      this.resetAllComponents();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applicationId: null,
        projectName: null,
        researchField: null,
        deptId: null,
        projectLeader: null,
        startDate: null,
        approvalTime: null,
        funding: null,
        progress: null,
        status: null,
        phone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRows: [  // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      };
      this.sciProjectTopicList = [];
      this.sciProjectMemberList = [];
      this.sciProjectBudgetList = [];
      this.sciProjectTaskList = [];
      this.activeStep = 0;
      this.applicationId = null;
      this.formData = {
        fileRows: []
      }
      this.resetForm("form");
    },

    resetView() {
      this.formView = {
        id: null,
        applicationId: null,
        projectName: null,
        researchField: null,
        deptId: null,
        projectLeader: null,
        startDate: null,
        approvalTime: null,
        funding: null,
        progress: null,
        status: null,
        phone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRows: [  // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      };
      this.sciProjectTopicList = [];
      this.sciProjectMemberList = [];
      this.sciProjectBudgetList = [];
      this.sciProjectTaskList = [];
      this.sciFundingAnnualList = [];
      this.resetForm("formView");
    },
    // 重置所有子组件
    resetAllComponents() {
      if (this.$refs.projectMember) {
        this.$refs.projectMember.resetData();
      }

      if (this.$refs.projectTask) {
        this.$refs.projectTask.resetData();
      }

      // if (this.$refs.budgetComponent) {
      //   this.$refs.budgetComponent.initBudgetList();
      // }
    },
    handleDatetimeUpdate(index, datetime) {
      // Update the corresponding uploadTime field
      this.$set(this.form.fileRows[index], 'uploadTime', datetime);
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeApprovalTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.readonlyApplicationId = false;
      this.title = "添加立项管理";
      this.form.fileRows[0].uploader = this.username;
      this.isEditing = false;
      // this.getApplicationInfo(false);
      // this.getApplicationList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProjectInfo(id).then(response => {
        this.form = response.data;
		    this.sciProjectTopicList = response.data.sciProjectTopicList;
        this.sciProjectMemberList = response.data.sciProjectMemberList;
        this.sciFundingAnnualList = response.data.sciFundingAnnualList;
        this.open = true;
        this.readonlyApplicationId = false;
        this.title = "修改立项管理";
        this.applicationId = this.form.applicationId;
        this.isEditing = true;
        this.readonlyApplicationId = true;
        // this.getApplicationInfo(true);
        // this.getApplicationList();
      });
    },

    handleApplicationIdChange(value) {
      if (value !== null && value !== undefined) {
        this.applicationId = value;
        this.getApplicationInfo(false); // 示例：加载项目详情
      }
    },

    handleView(row) {
      this.resetView();
      const id = row.id || this.ids
      getProjectInfo(id).then(response => {

        if (response.data && response.data.fileRows) {
          response.data.fileRows = response.data.fileRows.map(fileRow => {
            try {
              // 如果fileInfo是字符串则转换为数组，否则保持原样
              fileRow.fileInfo = typeof fileRow.fileInfo === 'string'
                ? JSON.parse(fileRow.fileInfo)
                : fileRow.fileInfo;
            } catch (e) {
              console.error('fileInfo解析失败：', e);
              fileRow.fileInfo = [];
            }
            return fileRow;
          });
        }
        // 绑定 sciProjectTopicList 和 sciProjectMemberList 到 formView
        this.formView = {
          ...response.data,
          sciProjectTopicList: response.data.sciProjectTopicList || [],
          sciProjectMemberList: response.data.sciProjectMemberList || [],
          sciProjectBudgetList: response.data.sciProjectBudgetList || [],
          sciProjectTaskList: response.data.sciProjectTaskList || [],
          sciFundingAnnualList: response.data.sciFundingAnnualList || []
        };

        this.drawer = true;
      });
    },
    handleDownload(file) {
      const fileName = file.url; // 替换为实际的文件名
      downloadMinioFile(fileName);
    },

    getApplicationInfo(editFlag) {
      if(this.applicationId!==null && this.applicationId!==undefined)
      {
        getAppSubmit(this.applicationId).then(response => {
            if (response.data && response.data.fileRows) {
              response.data.fileRows = response.data.fileRows.map(fileRow => {
                try {
                  // 如果fileInfo是字符串则转换为数组，否则保持原样
                  fileRow.fileInfo = typeof fileRow.fileInfo === 'string'
                    ? JSON.parse(fileRow.fileInfo)
                    : fileRow.fileInfo;
                } catch (e) {
                  console.error('fileInfo解析失败：', e);
                  fileRow.fileInfo = [];
                }
                return fileRow;
              });
            }
            this.formData = response.data;
            // 自动设置 form.publishId 的值
            if(!editFlag){
              this.form.applicationId = response.data.id;
              this.form.projectName = response.data.projectName;
              this.form.researchField = response.data.researchField;
              this.form.deptId = response.data.deptId;
              this.form.projectLeader = response.data.applicant;
              this.form.funding = response.data.funding;
              this.form.phone = response.data.phone;
            }


          }).catch(err => {
            this.$message.error("加载申报信息失败");
          });
        }
    },


    /** 提交按钮 */
    submitForm() {
       this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.form.fileRows || this.form.fileRows.length === 0) {
            this.$message.error('请上传文件');
            return;
          }
          for (let i = 0; i < this.form.fileRows.length; i++) {
            const row = this.form.fileRows[i];
            if (!row.fileClassName || row.fileClassName.trim() === '') {
              this.$message.error(`第 ${i + 1} 行文件类型不能为空`);
              return;
            }

            if (!row.fileInfo || JSON.parse(row.fileInfo).length === 0) {
              this.$message.error(`第 ${i + 1} 行附件不能为空`);
              return;
            }
          }
          this.form.sciProjectTopicList = this.sciProjectTopicList;
          this.form.sciProjectMemberList = this.sciProjectMemberList;
          this.form.sciFundingAnnualList = this.sciFundingAnnualList;
          // 提交前注入子组件数据
          this.form.task = this.taskData;
          if (this.form.id != null) {
            updateProjectInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProjectInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
     /** 删除按钮操作 */
     handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(function() {
        return delProjectInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

	/** 科研项目课题序号 */
    rowSciProjectTopicIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 科研项目课题添加按钮操作 */
    handleAddSciProjectTopic() {
      let obj = {};
      obj.topicName = "";
      obj.progress = "";
      obj.status = "";
      obj.createdBy = "";
      obj.createdTime = "";
      obj.updatedBy = "";
      obj.updatedTime = "";
      this.sciProjectTopicList.push(obj);
    },
    /** 科研项目课题删除按钮操作 */
    handleDeleteSciProjectTopic() {
      if (this.checkedSciProjectTopic.length == 0) {
        this.$modal.msgError("请先选择要删除的科研项目课题数据");
      } else {
        const sciProjectTopicList = this.sciProjectTopicList;
        const checkedSciProjectTopic = this.checkedSciProjectTopic;
        this.sciProjectTopicList = sciProjectTopicList.filter(function(item) {
          return checkedSciProjectTopic.indexOf(item.id) == -1
        });
      }
    },

      /** 复选框选中数据 */
    handleSciProjectTopicSelectionChange(selection) {
      this.checkedSciProjectTopic = selection.map(item => item.id)
    },

    /** 科研项目课题添加按钮操作 */
    handleAddSciProjectMember() {
      let obj = {};
      obj.userId = "";
      obj.nickName = "";
      obj.role = "";
      obj.topicId = "";
      this.sciProjectMemberList.push(obj);
    },
    /** 科研项目课题删除按钮操作 */
    handleDeleteSciProjectMember() {
      if (this.checkedSciProjectMember.length == 0) {
        this.$modal.msgError("请先选择要删除的成员数据");
      } else {
        const sciProjectMemberList = this.sciProjectMemberList;
        const checkedSciProjectMember = this.checkedSciProjectMember;
        this.sciProjectMemberList = sciProjectMemberList.filter(function(item) {
          return checkedSciProjectMember.indexOf(item.index) == -1
        });
      }
    },




    /** 复选框选中数据 */
    handleSciProjectMemberSelectionChange(selection) {
      this.sciProjectMemberList = selection.map(item => item.index)
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/projectInfo/export', {
        ...this.queryParams
      }, `projectInfo_${new Date().getTime()}.xlsx`)
    },




    addRow() {
      this.form.fileRows.push({
        fileClassName: '',
        uploader: this.username,
        uploadTime: '',
        fileInfo: [],
      });
    },
    removeRow(index) {
      if (this.form.fileRows.length > 1) {
        this.form.fileRows.splice(index, 1);
      } else {
        this.$message.warning('至少需要保留一行');
      }
    },

    formatStatus(status) {
      if (status == null) return '';

      switch (status) {
        case 0:
          return '未通过';
        case 1:
          return '申报中';
        case 2:
          return '已通过';
        default:
          return '';
      }
    },
    getDeptList() {
      listDept().then(response => {
        this.deptList = response.data.filter(dept => dept.deptId !== 100);      });
    },
    getDeptLabel(deptId) {
      const dept = this.deptList.find(d => d.deptId === deptId);
      return dept ? dept.deptName : '';
    },
    getApplicationList() {
      listAppSubmit().then(response => {
        this.applicationList = response.rows;
        if (!this.isEditing) {
          const establishedApplicationIds = this.projectInfoList.map(p => p.applicationId);
          this.selectApplicationList = response.rows.filter(item => item.status === 2 && !establishedApplicationIds.includes(item.id));
        } else {
          // 修改时只过滤 status !== 0
          this.selectApplicationList = response.rows.filter(item => item.status === 2);
        }
      });
    },

    getApplicationLabel(applicationId) {
      const application = this.applicationList.find(p => p.id === applicationId);
      return application ? application.projectName : '';
    },


    addMember() {
      if (!this.form.id) {
        this.$message.error("请先填写并提交项目基本信息");
        return;
      }

      const newMember = {
        projectId: this.form.id,               // 当前项目ID（必填）
        topicId: this.memberForm.topicId || null, // 非必填，空值为 null
        userId: this.memberForm.userId,
        nickName: this.memberForm.nickName,
        role: this.memberForm.role
      };

      this.form.members.push(newMember);

      // 清空临时输入框
      this.memberForm.userId = '';
      this.memberForm.nickName = '';
      this.memberForm.role = '';
      this.memberForm.topicId = null; // 保留原有课题选择状态
    },
    removeMember(index) {
      this.form.members.splice(index, 1);
    },


    nextStep() {
      if (this.activeStep === 6) {
        this.submitForm();
      } else {
        let valid = false;
        switch (this.activeStep) {
          case 0: valid = this.validateStep0(); break;
          case 1: valid = this.validateStep1(); break;
          case 2: valid = this.validateStep2(); break;
          case 3: valid = this.validateStep3(); break;
          case 4: valid = this.validateStep4(); break;
          case 5: valid = this.validateStep5(); break;
          case 6: valid = this.validateStep6(); break;
          default: valid = true;
        }

        if (valid) {

          this.activeStep += 1;
          // 当从课题分解切换到后，将完整的课题信息传给子组件
          if(this.activeStep===2){
            this.intactTopicList = this.sciProjectTopicList;
          }
        } else {
          // this.$message.error(`第 ${this.activeStep + 1} 步数据不完整，请补充`);
        }
      }
    },


    prevStep() {
      this.activeStep -= 1;
    },


    handleBudgetSubmit(budgetData) {
    // 数据结构示例：
    // [{
    //   projectId: 123,
    //   templateId: 2,
    //   subjectId: 12,
    //   topicId: 456,
    //   fiscalFunds: 0.00,
    //   selfFunds: 0.00
    // }]

    // 调用API提交数据
    this.$api.submitBudget(budgetData)
      .then(() => this.$message.success('预算提交成功'))
      .catch(err => this.$message.error(`提交失败: ${err.message}`));
  },


    validateStep0() {
      const { projectName, researchField, deptId, projectLeader, approvalTime, startDate, endDate, funding, phone } = this.form;
      if(!(projectName && researchField && deptId && projectLeader && approvalTime && startDate && endDate && funding && phone))
      {
        this.$message.error('信息填写不完整，请补充完整');
        return false;
      }
      return true;
    },
    validateStep1() {
      if (this.sciProjectTopicList.length === 0) {
        this.$message.error('请至少添加一个课题');
        return false;
      }

      for (let i = 0; i < this.sciProjectTopicList.length; i++) {
        const row = this.sciProjectTopicList[i];
        if (!row.topicName || !row.leader) {
          this.$message.error(`第 ${i + 1} 行课题信息不完整，请填写课题名称和负责人`);
          return false;
        }
      }

      return true;
    },
    validateStep2() {
      if (this.sciProjectMemberList.length === 0) {
        this.$message.error('请至少添加一名成员');
        return false;
      }



      return true;
    },
    validateStep3() {
      if (this.sciProjectTaskList.length === 0) {
        this.$message.error('请至少添加一项任务');
        return false;
      }
      return true;
    },


    validateStep4() {
      // 直接使用 this.budgetData 而不是从组件引用获取
      console.log("预算数据："+this.budgetData);
      if (!this.budgetData || this.budgetData.length === 0) {
        this.$message.warning('预算数据为空，请先填写预算信息');
        return false;
      }

      const errors = [];

      this.budgetData.forEach((row, index) => {
        if (row.fiscalFunds=== null || row.fiscalFunds === '') {
          errors.push(`第 ${index + 1} 行 财政经费 不能为空`);
        }

        if (row.selfFunds=== null || row.selfFunds === '')  {
          errors.push(`第 ${index + 1} 行 自筹经费 不能为空`);
        }
      });

      if (errors.length > 0) {
        this.$notify.error({
          title: '校验失败',
          message: errors.join('；'),
          duration: 3000,
          position: 'bottom-right'
        });
        return false;
      } else {
        this.sciProjectBudgetList = this.budgetData;
        this.form.sciProjectBudgetList = this.budgetData;
        return true;
      }
    },

    validateStep5() {
      if (this.sciFundingAnnualList.length === 0) {
        this.$message.error('请至少添加一项年度经费');
        return false;
      }
      return true;
    },
    validateStep6() {
      return this.form.fileRows.some(row => row.fileInfo.length > 0);
    },

    getTopicName(topicId) {
      if (!topicId) return '无';
      const topic = this.formView.sciProjectTopicList.find(t => t.id === topicId);
      return topic ? topic.topicName : '未知课题';
    },
    // 添加更新预算数据的方法
    updateBudgetData(data) {
      console.log("更新预算数据："+data);
      this.budgetData = data;
      // 可以在这里处理预算数据，比如保存到表单中
      this.form.sciProjectBudgetList = data;
    },


  }
};
</script>
<style lang="scss" scoped>
.black-bold-header .el-card__header span {
  font-weight: bold;
  font-family: "SimHei", sans-serif;
}

.dialog-content {
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.step-content {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.black-bold-header .el-card__header span {
  font-weight: bold;
  font-family: "SimHei", sans-serif;
}

// 滚动条样式优化
.step-content::-webkit-scrollbar {
  width: 6px;
}

.step-content::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.step-content::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  border-radius: 3px;
}
</style>


